package legumes.client.ui.basket.slate;

import legumes.client.resources.PNResources;
import legumes.client.services.callbacks.AddNewProductMarketCallback;
import legumes.client.services.util.rpc.RPCCallSequencer;
import legumes.client.ui.widgets.form.item.ProductCategorytFormItem;
import legumes.client.ui.widgets.form.item.ProductNameFormItem;
import legumes.client.ui.widgets.form.item.ProductVarietytFormItem;
import legumes.shared.domain.NewProductMarket;
import legumes.shared.domain.Product;
import legumes.shared.domain.ProductCategory;
import legumes.shared.domain.ProductVariety;

import com.google.gwt.core.client.GWT;
import com.smartgwt.client.core.Function;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.events.CloseClickHandler;
import com.smartgwt.client.widgets.events.CloseClientEvent;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.ButtonItem;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
import com.smartgwt.client.widgets.form.fields.events.ClickEvent;
import com.smartgwt.client.widgets.form.fields.events.ClickHandler;
import com.smartgwt.client.widgets.layout.HLayout;

public class NewMarketProductEditionWindow extends Window {

	private NewProductMarket newProductMarket;
	private ButtonItem biValidate;
	private ButtonItem biCancel;
	
	private ProductCategorytFormItem fiProductCategory;
	private ProductVarietytFormItem fiProductVariety;
	private ProductNameFormItem fiProductName;
	private String productNameToCreate;
	private DynamicForm form;
	private Product createdProduct = null;
	private Function fctCalledOnProductCreated;
	
	public NewMarketProductEditionWindow(String productNameToCreate_) {
		super();
		productNameToCreate = productNameToCreate_;
		setWidth(480);
		setHeight(200);
		String titleWindow = "Nouveau produit";
		setTitle("<img src=\""
				+ PNResources.INSTANCE.shoppingChartIcon().getURL()
				+ "\" />&nbsp;" + titleWindow);

		setShowCloseButton(true);
		setShowMinimizeButton(false);
		setCanDrag(true);
		setCanDragReposition(true);
		setIsModal(true);
		setShowModalMask(true);  
		setAutoCenter(true);
		addCloseClickHandler(new CloseClickHandler() {  
            public void onCloseClick(CloseClientEvent event) {  
                destroy();  
            }  
        });  
		buildPanel();
		show();
	}
	
	
	public void setFctCalledOnProductCreated(Function fctCalledOnProductCreated_){
		fctCalledOnProductCreated = fctCalledOnProductCreated_;
	}
	
	private void buildPanel() {
		HLayout mainLayout = new HLayout();
		mainLayout.setMargin(10);
		
		mainLayout.setMembers( buildFormPanel() );
		
		addItem(mainLayout);
	}
	
	private Canvas buildFormPanel(){
		form = new DynamicForm();
		form.setPadding(5);  
		form.setWidth("*");
		form.setLayoutAlign(Alignment.CENTER);
		form.setNumCols(4);
		form.setValidateOnExit(true);
		
		fiProductName = new ProductNameFormItem();
		fiProductName.setStartRow(true);
		fiProductName.setEndRow(true);
		fiProductName.setValue(productNameToCreate);
		
		fiProductVariety = new ProductVarietytFormItem("");
		fiProductVariety.addChangedHandler(new ChangedHandler() {
			
			@Override
			public void onChanged(ChangedEvent event) {
				Object value = event.getValue();
				if(value!=null){
					String variety = value.toString();
					ProductVariety pv = fiProductVariety.findProductVariety(variety);
					if(pv!=null){
						fiProductCategory.setValue(pv.getProductCategory().getName());
					}
				}
			}
		});
		
		fiProductCategory = new ProductCategorytFormItem("");
		
    	biValidate = new ButtonItem("AddToBasket", "Cr&eacute;er");
    	biValidate.setAutoFit(true);
    	biValidate.setColSpan(1);
    	biValidate.setAlign(Alignment.CENTER);
    	biValidate.setStartRow(true);
    	biValidate.setEndRow(false);
    	biValidate.setIcon( PNResources.INSTANCE.addIcon().getURL() );
    	biValidate.addClickHandler( createClickhandler() );
    	
    	biCancel = new ButtonItem("RemoveFromBasket", "Annuler");
    	biCancel.setIcon( PNResources.INSTANCE.cancelIcon().getURL() );
    	biCancel.setAlign(Alignment.CENTER);
    	biCancel.setStartRow(false);
    	biCancel.setEndRow(false);
    	biCancel.addClickHandler( new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				NewMarketProductEditionWindow.this.destroy();
			}
		});
    	
    	form.setFields(fiProductName, fiProductVariety, fiProductCategory, 
    			biValidate, biCancel);

        return form;
	}
	
	private ClickHandler createClickhandler(){
		return new ClickHandler() {
			
        	private Product createNewProduct(String newProductName_, 
        			ProductVariety newProductVariety, 
        			ProductCategory newProductCategory){
        		Product p = new Product();
				p.setName(newProductName_);
				p.setProductVariety(newProductVariety);
//				p.setProductCategory(newProductCategory);
				return p;
        	}
        	
			@Override
			public void onClick(ClickEvent event) {
				if( form.validate() ){
					try{
						String newProductName = (String)fiProductName.getValue();
						ProductVariety newProductVariety = fiProductVariety.getProductVariety();
						ProductCategory newProductCategory = fiProductCategory.getProductCategory();
						
						newProductMarket = new NewProductMarket();
						newProductMarket.setComment("");
						newProductMarket.setProduct(createNewProduct(newProductName, newProductVariety, newProductCategory));
						
						saveOnServer();
					} catch(Exception e_){
						GWT.log("Basket outside panel : onEditComplete ", e_);
					}
					
				}
            }
		};
	}
	
	private void saveOnServer(){
		RPCCallSequencer callSequencer = new RPCCallSequencer("Enregistrement en cours...");
		final AddNewProductMarketCallback addNewProductMarketCallback = new AddNewProductMarketCallback(
				newProductMarket);
		callSequencer.addCall(addNewProductMarketCallback);
		callSequencer.addRunnable(new Runnable() {
			public void run() {
				Product pr = addNewProductMarketCallback.getCreatedProduct();
				if(pr == null){
					SC.say("Erreur", "Création du nouveau produit impossible, vérifier que ce produit n'existe pas déjà");
				} else {
					createdProduct = pr;
				}
				if(fctCalledOnProductCreated!=null){
					fctCalledOnProductCreated.execute();
				}
				NewMarketProductEditionWindow.this.destroy();
			}
		});
		callSequencer.callSequence();
	}

	public Product getCreatedProduct() {
		return createdProduct;
	}
	
	
}
